from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User


from .utils import check_save_user_token


class QQAuthUserSerializer(serializers.Serializer):
    """QQ登录创建用户序列化器"""
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        # 检验access_token
        access_token = attrs.get('access_token')
        # 获取身份凭证
        openid = check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的access_token')

        # 将openid放在校验字典中，后面会使用
        attrs['openid'] = openid

        # 检验短信验证码是否正确
        redis_conn = get_redis_connection('verify_codes')
        # 获取当前用户的手机号
        mobile = attrs.get('mobile')
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        # 获取当前传过来的验证码
        sms_code = attrs.get('sms_code')
        if real_sms_code.decode() != sms_code: # 注意解码
            raise serializers.ValidationError('验证码错误')


        try:
            # 判断手机号是否是已经存在的用户，还是新用户
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 出现异常是新用户
            pass
        else:
            # 此手机已经注册过
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('用户已存在，但密码不正确')
            else:
                attrs['user'] = user

        return attrs

    def create(self, validated_data):
        """把openid和user进行绑定"""
        user = validated_data.get('user')
        if not user:
            # 用户不存在,新建用户
            user = User.objects.create_user(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],

            )

            # 让user和openid绑定
            OAuthQQUser.objects.create(
                openid=validated_data['openid'],
                user=user
            )


        # 返回用户数据
        return user
